<template>
  <div class="app-container">
    <!-- 折线图卡片 -->
    <el-card class="box-card" style="margin-bottom: 20px">
      <div id="attendanceLineChart" style="width: 100%; height: 400px"></div>
    </el-card>

    <!-- 饼图卡片 -->
    <el-card class="box-card">
      <el-select
        v-model="selectedCourse"
        placeholder="请选择课程"
        style="width: 300px; margin-bottom: 20px"
        @change="updatePieChart"
      >
        <el-option
          v-for="item in selectBoxList"
          :key="item.courseRecordId"
          :label="`${item.courseName}（${item.createTime}）`"
          :value="item.courseRecordId"
        />
      </el-select>
      <div id="statusPieChart" style="width: 100%; height: 350px"></div>
    </el-card>
  </div>
</template>

<script>

import {analysisAttendanceRecord} from "@/api/attendance/attendanceRecord";
import {analysisSignRecordForTeacher, listSignRecordForTeacher} from "@/api/attendance/signRecord";
import * as echarts from 'echarts'

export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 查询参数
      queryParams: {
        courseName: null,
        attendanceTime: null,
        attendanceType: null,
        createTime: null
      },
      attendanceRecordList: [],
      selectBoxList: [],
      dataAnalysis: [],
      selectedCourse: null,
      lineChart: null,  // 折线图实例
      pieChart: null    // 饼图实例
    }
  },
  created() {
    this.getList();
  },
  mounted() {
    window.addEventListener('resize', this.handleResize);
    // 新增：在数据获取并初始化图表后，检查是否需要立即渲染饼图
    this.$nextTick(() => {
      if (this.selectBoxList.length && this.pieChart) {
        this.selectedCourse = this.selectBoxList[0].courseRecordId;
        this.renderPieChart();
      }
    });
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  // 新增数据加载状态监控
  watch: {
    // 深度监听dataAnalysis变化
    dataAnalysis: {
      deep: true,
      handler(newVal) {
        if (this.selectedCourse && this.pieChart &&!this.pieChart._option) {
          this.renderPieChart();
        }
      }
    }
  },
  methods: {
    /** 查询考勤记录列表 */
    getList() {
      this.loading = true;
      analysisAttendanceRecord(this.queryParams).then(async response => {
        this.attendanceRecordList = response.rows;

        // 构建唯一的下拉框选项列表
        const seenIds = new Set();
        this.selectBoxList = response.rows.reduce((acc, item) => {
          if (!seenIds.has(item.courseRecordId)) {
            seenIds.add(item.courseRecordId);
            acc.push({
              courseRecordId: item.courseRecordId,
              courseName: item.courseName,
              createTime: item.createTime
            });
          }
          return acc;
        }, []);
        if (this.selectBoxList.length > 0) {
          this.selectedCourse = this.selectBoxList[0].courseRecordId;
        }

        // 使用Promise.all同步所有子请求
        const promises = this.attendanceRecordList.map(item =>
          this.getAttendanceData(item.courseRecordId)
        );

        await Promise.all(promises); // 等待所有考勤数据加载

        // 此时dataAnalysis已完成填充
        this.$nextTick(() => {
          this.initCharts(); // 延迟到此处初始化图表
          this.loading = false;
        });
      });
    },
    /** 获取具体考勤数据 */
    getAttendanceData(courseRecordId) {
      return new Promise((resolve, reject) => {
        const query = {courseRecordId: courseRecordId};
        analysisSignRecordForTeacher(query).then(response => {
          const total = response.total;
          const statusMap = {  // 状态映射配置
            0: 'onTime',
            1: 'late',
            2: 'makeUp',
            3: 'absent',
            4: 'leave',
            5: 'unsigned'
          };

          // 初始化统计对象
          const statusCount = Object.keys(statusMap).reduce((acc, key) => {
            acc[statusMap[key]] = 0;
            return acc;
          }, {});

          // 统计各状态人数
          if (response.rows && response.rows.length) {
            response.rows.forEach(record => {
              const statusKey = statusMap[record.signStatus];
              if (statusKey) statusCount[statusKey]++;
            });
          }

          // 构建分析数据对象
          const analysisItem = {
            courseRecordId,
            total,
            ...statusCount,
            // 计算出席率（用于折线图）
            attendanceRate: (statusCount.onTime + statusCount.late + statusCount.makeUp) / total
          };

          // 更新或添加数据
          const existingIndex = this.dataAnalysis.findIndex(
            item => item.courseRecordId === courseRecordId
          );
          if (existingIndex > -1) {
            this.$set(this.dataAnalysis, existingIndex, analysisItem);
          } else {
            this.dataAnalysis.push(analysisItem);
          }
          resolve();
        }).catch(error => {
          reject(error);
        });
      });
    },
    /** 初始化图表 */
    initCharts() {

      // 销毁旧实例
      if (this.lineChart) {
        this.lineChart.dispose();
      }
      if (this.pieChart) {
        this.pieChart.dispose();
      }
      // 折线图初始化
      this.lineChart = echarts.init(document.getElementById('attendanceLineChart'));

      // 饼图初始化
      this.pieChart = echarts.init(document.getElementById('statusPieChart'));

      // 初始渲染
      this.renderLineChart();

      if (this.selectBoxList.length) {
        this.selectedCourse = this.selectBoxList[0].courseRecordId;
        this.renderPieChart();
      }
    },

    /** 渲染折线图 */
    renderLineChart() {

      this.lineChart.showLoading();
      const chartData = this.attendanceRecordList
        .sort((a, b) => new Date(a.createTime) - new Date(b.createTime))
        .map(item => {
          // 从dataAnalysis中匹配对应数据
          const analysis = this.dataAnalysis.find(
            d => d.courseRecordId === item.courseRecordId
          );
          return {
            name: `${item.createTime || '未知时间'}\n${item.courseName || '未知课程'}`,
            value: analysis ? analysis.attendanceRate : 0, // 双重保护空值
            id: item.courseRecordId
          };
        });
      // 空数据状态处理
      if (chartData.length === 0) {
        this.lineChart.setOption({
          graphic: {
            type: 'text',
            style: {
              text: '暂无出勤记录',
              fontSize: 18,
              fill: '#999'
            },
            left: 'center',
            top: 'center'
          }
        });
        return;
      }

      const option = {
        title: { text: '课程出勤率趋势', left: 'center' },
        tooltip: {
          formatter: params => {
            const item = chartData.find(d => d.name === params.name);
            if (!item) return '无有效数据';

            const [course, time] = item.name.split('\n');
            return `课程：${course}<br/>
              时间：${time}<br/>
              出勤率：${(item.value * 100).toFixed(1)}%`;
          }
        },
        xAxis: {
          type: 'category',
          data: chartData.map(d => d.name),
          axisLabel: {rotate: 30}
        },
        yAxis: {
          type: 'value',
          axisLabel: {formatter: '{value}%'},
          min: 0,
          max: 100
        },
        series: [{
          type: 'line',
          data: chartData.map(d => (d.value * 100).toFixed(1)),
          smooth: true,
          areaStyle: {color: '#c8e6c9'},
          lineStyle: {color: '#4CAF50'}
        }]
      };
      this.lineChart.setOption(option);
      this.lineChart.hideLoading();
    },

    /** 渲染饼图 */
    renderPieChart() {
      const analysisItem = this.dataAnalysis.find(
        d => d.courseRecordId === this.selectedCourse // 直接使用绑定值
      );
      const statusData = [
        {name: '准时', value: analysisItem?.onTime || 0},
        {name: '迟到', value: analysisItem?.late || 0},
        {name: '补签', value: analysisItem?.makeUp || 0},
        {name: '旷课', value: analysisItem?.absent || 0},
        {name: '请假', value: analysisItem?.leave || 0},
        {name: '未签到', value: analysisItem?.unsigned || 0}
      ];
      const option = {
        color: ['#67C23A', '#E6A23C', '#9C27B0', '#909399', '#409EFF', '#F56C6C'],
        title: {
          text: '签到状态分布',
          left: 'center',
          subtext: `总人数：${analysisItem?.total || 0}`
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br/>{b}: {c}人 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: statusData.map(d => d.name)
        },
        series: [{
          name: '签到状态',
          type: 'pie',
          radius: ['35%', '60%'],
          avoidLabelOverlap: false,
          label: {
            show: true,
            formatter: '{b}: {d}%',
          },
          data: statusData,
          itemStyle: {
            borderRadius: 5,
            borderColor: '#fff',
            borderWidth: 2
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            label: {
              fontWeight: 'bold'
            }
          }
        }]
      };
      this.pieChart.setOption(option);
    },

    /** 窗口resize处理 */
    handleResize() {
      this.lineChart?.resize();
      this.pieChart?.resize();
    },

    /** 更新饼图 */
    updatePieChart() {
      this.renderPieChart();
    }
  }
}
</script>
